package com.facesteel.speech_play;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;

public class SpeechPlayHelper {

    private static String TAG = "| SpeechPlayHelper | Flutter | Android | ";
    private SpeechPlayHelper() {
    }
    private static final class SingleHolder {
        private static final SpeechPlayHelper single = new SpeechPlayHelper();
    }

    public static SpeechPlayHelper getInstance() {
        return SpeechPlayHelper.SingleHolder.single;
    }


    private boolean dartIsReady = false;

    private Handler mHandler;

    private MethodChannel channel;

    public MethodChannel getChannel() {
        return channel;
    }

    public Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        return mHandler;
    }
    public void setMethodChannel(MethodChannel channel) {
        this.channel = channel;
    }

    public void setDartIsReady(boolean isReady) {
        dartIsReady = isReady;
    }


    public void onListenerCompleted(){
        if(dartIsReady){
            Map<String, Object> data = new HashMap<>();
            data.put("code", "1");
            runMainThread(data,  "onListenerCompleted");
        }
    }

    public void onListenerPlayTime(double time){
        if(dartIsReady){
            Map<String, Object> data = new HashMap<>();
            data.put("time", time);
            runMainThread(data,  "onListenerPlayTime");
        }
    }

    public void  onSwitchSpeaker(boolean status) {
        if(dartIsReady){
            Map<String, Object> data = new HashMap<>();
            data.put("status", status);
            runMainThread(data,  "onSwitchSpeaker");
        }
    }

    public void runMainThread(final Map<String, Object> map, final String method) {
        getHandler().post(() -> {
            if (null != channel) {
                channel.invokeMethod(method, map);
            } else {
                Log.d(TAG, "channel is null do nothing");
            }
        });
    }
}
